iT邦幫忙

2023 iThome 鐵人賽

DAY 10
0
自我挑戰組

C# 和 SQL 探索之路 - 2系列 第 10

Day 10: C# 再寫一次 Lambda

  • 分享至 

  • xImage
  •  

大家好,今天是第十天了!
完成三分之一,繼續加油 /images/emoticon/emoticon37.gif


用 Lambda 找出集合中特定條件下的數量,可使用 Count 語法。
以下範例可找出 Receiver 類別中,name 以 J 開頭的物件數量:

    protected class Receiver{
    	public string name;
    	public string email;

    	public Receiver(string n, string m){
        	name = n;
        	email = m;
    	}
	}

	public void Run(){
    	List<Receiver> receiver = new List<Receiver>();

    	receiver.Add(new Receiver("Jack", "Jack@gmail.com"));
    	receiver.Add(new Receiver("Justin", "Justin@gmail.com"));
    	receiver.Add(new Receiver("Eddy", "Eddy@hotmail.com"));
    	receiver.Add(new Receiver("Jeff", "Chen.Jeff@gmail.com"));

    	int jCount = receiver.Count(n => n.name.StartsWith("J"));
    	Console.WriteLine("Receiver start with J:" + jCount);

    }

結果為:

Receiver start with J:3

若要使用 Lambda 排序,可以使用 OrderBy()OrderByDescending() 對欄位分別作遞增、遞減排序。如果需要接著對其它欄位排序,還可以使用 ThenBy()ThenByDescending()

延續上方的例子,修改內部的 Run 方法,要求以 Receiver 類別的 email 欄位遞增、遞減排序:

    public void Run(){
    	List<Receiver> receiver = new List<Receiver>();

    	receiver.Add(new Receiver("Jack", "Jack@gmail.com"));
    	receiver.Add(new Receiver("Justin", "Justin@gmail.com"));
    	receiver.Add(new Receiver("Eddy", "Eddy@hotmail.com"));
    	receiver.Add(new Receiver("Jeff", "Chen.Jeff@gmail.com"));

    	IOrderedEnumerable<Receiver> AscReceiver = receiver.OrderBy(n => n.email);
    	foreach(Receiver r in AscReceiver){
        	Console.WriteLine(r.email + "(" + r.name + ")");
    	}

    	IOrderedEnumerable<Receiver> DescReceiver = receiver.OrderByDescending(n => n.email);
    	foreach(Receiver r in DescReceiver){
        	Console.WriteLine(r.email + "(" + r.name + ")");
    	}
	}

輸出結果為:

Chen.Jeff@gmail.com(Jeff)
Eddy@hotmail.com(Eddy)
Jack@gmail.com(Jack)
Justin@gmail.com(Justin)

Justin@gmail.com(Justin)
Jack@gmail.com(Jack)
Eddy@hotmail.com(Eddy)
Chen.Jeff@gmail.com(Jeff)

參考資料

C# 3.0 極簡風 - Lambda Expression-黑暗執行緒
c# - Multiple Order By with LINQ - Stack Overflow
c# - Get item count of a list<> using Linq - Stack Overflow


上一篇
Day 9: C# 常用文件註解標籤
下一篇
Day 11: ASP.NET 如何保存資訊、重導向的差異
系列文
C# 和 SQL 探索之路 - 230
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言